var editRow = 0;

var parentid;
var sort;
//页面初始化
$(function(){
	initTable();

	//关闭新增窗口
	$("#closeBtn").click(function() {
		backendCommon.closeWin("sectionWin");
	});
});
//初始化表格
function initTable(){
	$('#tt').treegrid({
		width : backendCommon.getWidth(0.97),
		height : backendCommon.getHeight(0.94),
		url:mainDomain+'/section/sectionTree.action',
		rownumbers : true,
		animate : true,
		loadMsg : '数据加载中...',
		fitColumns : true,
		singleSelect : true,
	    idField:'id',    
	    treeField:'sectionName',    
	    columns:[[    
	        {title:'<b>[<font color="red">栏目</font>]</b>',field:'sectionName',width:200}, 
	        {title:'栏目排序',field:'sort',width:120,align:'center',
	        	formatter : function(value, rec, index) {
					var str = "";
					if(rec.id != -1){
						if(rec.sectionType == 0){
							str = "<font color='blue' size='3'><strong>" + value + "</strong></font>";
						} else {
							str = "<font color='red'>" + value + "</font>";
						}
	        		}
					return str;
				},
				editor:'text'	
	        },   
	        {title:'创建人',field:'createByName',width:100,align:'center'},    
	        {title:'创建时间',field:'createTime',width:160,align:'center'
	        },    
	        {title:'更新人',field:'updateByName',width:100,align:'center'},    
	        {title:'更新时间',field:'updateTime',width:160,align:'center'
	        },
	        {title:'状态',field:'isDelete',width:80,align:'center',
	        	formatter : function(value, rec, index) {
					var str = "";
					if(value == 0) {
						str = "<font color='bule'>使用中</font>";
					} else if(value == 1){
						str = "<font color='red'>已停用</font>";
					}
					return str;
				}	
	        },
	        {title : '栏目管理',field : 'opt',width:320,align : 'center',
				formatter : function(value, rec, index) {
					var str = "";
					if(rec.id == -1){
						str += '<div><a class="btn_blue06" href="javascript:void(0);" onclick="openAddSectionWin('+rec.id+');">新增</a></div>';
					}else{
						str += '<div><a class="btn_blue06" href="javascript:void(0);" onclick="updateSectionWin('+rec.id+');">修改</a></div>';
						if(rec.isDelete == 0) {
							str += '<div><a class="btn_blue06" data-name="'+rec.sectionName+'" href="javascript:void(0);" onclick="enableSection(this,'+rec.id+', 1);">下架</a></div>';
						} else {
							str += '<div><a class="btn_blue06" data-name="'+rec.sectionName+'"  href="javascript:void(0);" onclick="enableSection(this,'+rec.id+', 0);">启用</a></div>';
						}
					}
					
					return str;
				}
			}
	    ]],
	    onBeforeExpand : function(row) {
			// 节点展开时从该 URL 加载数据
			var url = mainDomain + '/section/sectionTreeByParentId.action?parentId='+row.id;
			$("#tt").treegrid("options").url = url;
			return true;
		},
		onLoadSuccess : function(row, data) {
			if(parentid == undefined){
				$("#tt").treegrid("expand",-1);
			}else{
				$("#tt").treegrid("expand",parentid);
			}
			return true;
		},
		onBeforeEdit : function(row) {
			row.editing = true;
			sort = row.sort;
			$('#tt').treegrid('refresh', row.id);
			editRow++;
		},
		onAfterEdit : function(row,changes) {
			row.editing = false;
			$('#tt').treegrid('refresh', row.id);
			editRow--;
		},
		onCancelEdit : function(row) {
			row.editing = false;
			$('#tt').treegrid('refresh', row.id);
			editRow--;
		},
		onDblClickCell : function(field,row) {
			if(editRow > 0) {
				$.messager.alert('提示', '其他数据正在编辑中，请保存后再执行其他操作', 'error');
				return;
			}
			$('#tt').datagrid('beginEdit', row.id);
			$("input.datagrid-editable-input").focus();
			$("input.datagrid-editable-input").keyup(function(e) {
				if(e.keyCode == 13) {
					saveSectionSort(field,row);
				}
			});
		}
	}).datagrid('acceptChanges');
}

//打开新增窗口
function openAddSectionWin() {
	//初始化窗口
	//清空隐藏属性，栏目ID
	$("#sectionId").val("");
	$("#parentSectionId").val("");
	backendCommon.formReset("sectionForm");
	backendCommon.openeWin('sectionWin');
	
	//获取所有的一级目录
	var opt = "";
	$.post(mainDomain+'/section/findFirstLevelSections.action',{},function(data){
		if(data!=null && data.sec!= null){
			opt += "<option value='0'>根目录</option>";
			$.each(data.sec,function(index,section){
				opt += "<option value='"+section.id+"'>--"+section.sectionName+"</option>";
			});
			$("#parentSectionSelect").html(opt);
		}
	},'json');
	
	$("#saveBtn").unbind('click').click(function() {
		addOrUpdateSectionInfo(true);
	});
}

//重新查询数据库，展示在弹出框中，并弹出编辑栏目窗口
function updateSectionWin(sectionId) {
	//查询数据库
	$.post(mainDomain+'/section/findSectionInfoById.action', {sectionId : sectionId}, function(result){
		if (result.success && result.state == 1) {
			//填充数据
			var sectionInfo = result.data.sectionInfoVO;
			if(sectionInfo != null) {
				$("#sectionId").val(sectionInfo.id);
				$("#sectionInfoNameIpt").val(sectionInfo.sectionName);
				$("#sectionInfoLabelIpt").val(sectionInfo.sectionLabel);
				$("#parentSectionSelect").find("option[value='"+sectionInfo.parentSectionId+"']").attr("selected",true);
				$("#sectionDescIpt").val(sectionInfo.sectionDesc);
				$("#parentSectionId").val(sectionInfo.parentSectionId);
				
				backendCommon.openeWin('sectionWin');
				$("#saveBtn").unbind('click').click(function() {
					addOrUpdateSectionInfo(false);
				});
			} else {
				$.messager.alert('提示', '返回数据为空', 'error');
			}
		} else {
			$.messager.alert('提示', result.message, 'error');
		}
	});
}

//新增、编辑栏目窗口
function addOrUpdateSectionInfo() {
	//选取填写数据
	var sectionName = $("#sectionInfoNameIpt").val();
	var sectionLabel = $("#sectionInfoLabelIpt").val();
	var parentSectionId = $("#parentSectionSelect").val();
	var oldParentSectionId = $("#parentSectionId").val();
	var sectionDesc = $("#sectionDescIpt").val();
	var id = $("#sectionId").val();
	//校验数据
	if(sectionName == '') {
		$.messager.alert('提示',"栏目名称不能为空！",'error');
		return false;
	}
	if(sectionName.length > 30) {
		$.messager.alert('提示',"栏目名称不能大于30个字符！",'error');
		return false;
	}
	if(sectionLabel != '' && sectionLabel.length > 30) {
		$.messager.alert('提示',"栏目别名不能大于30个字符！",'error');
		return false;
	}
	if(parentSectionId == '') {
		$.messager.alert('提示',"所属栏目不能为空！",'error');
		return false;
	}
	if(sectionDesc != '' && sectionDesc.length > 1000) {
		$.messager.alert('提示',"所属栏目不能大于1000个字符！",'error');
		return false;
	}
	//组装参数
	var param={
			'id':id,
			'sectionName':sectionName,
			'sectionLabel':sectionLabel,
			'parentSectionId':parentSectionId,
			'oldParentSectionId':oldParentSectionId,
			'sectionDesc':sectionDesc
	};
	
	//新增编辑栏目
	parentid = parentSectionId;
	$.post(mainDomain+'/section/addOrUpdateSectionInfo.action',param,function(result){
		if (result.success && result.state == 1) {
			$.messager.alert('提示', '保存成功！');
			backendCommon.closeWin('sectionWin');
			$("#tt").treegrid('reload',-1);
		}else{
			$.messager.alert('提示', result.message , 'error');
			return false;
		}
	},'json');
	
}

//保存排序结果
function saveSectionSort(field,row) {
	
	var t = $("#tt");
	t.treegrid('endEdit', row.id);
	//修改之前
	var sortVal = sort;
	//修改之后
	var sortAfter = row.sort;//  t.treegrid('getSelected').sort;
	
	if(!backendCommon.regIsNum(sortAfter)){
		$.messager.alert('提示', "排序只能输入数字", 'error');
		$("#tt").treegrid('reload',-1);
		return false;
	}
	parentid = row.parentSectionId;
	//修改之前和修改之后一样   不修改
	if(sortVal != sortAfter){
		//如果值不相同，则保存
		var param = {
				id : row.id,
				sort : sortAfter
		};
		//新增编辑栏目
		$.post(mainDomain+'/section/updateSectionSortById.action', param ,function(result){
			if (!result.success) {
				//如果失败，则提示错误信息
				$.messager.alert('提示', result.message, 'error');
			}
			//无论成功失败，都刷新列表
			$("#tt").treegrid('reload',-1);
		},'json');
	}
}

//启用或停用栏目
function enableSection($this,sectionId, status) {
	var sectionName = $($this).attr("data-name");
	var node = $("#tt").treegrid('find',sectionId);
	var tips = '';
	if(node.parentSectionId == 0){
		if(status == 1){
			tips = '确定要停用 " ' + sectionName +'" 下所有栏目主题和资讯？';
		}else{
			tips = '确定要启用 " ' + sectionName +'" 下所有栏目主题和资讯？';
		}
	}else{
		if(status == 1){
			tips = '确定要停用 " ' + sectionName +'" 栏目主题？';
		}else{
			tips = '确定要启用" ' + sectionName +'" 栏目主题？';
		}
	}
	if(confirm(tips)){
		var param = {
				id : sectionId,
				isDelete : status
		};
		parentid = node.parentSectionId;
		//启用停用栏目
		$.post(mainDomain+'/section/enableSectionById.action', param ,function(result){
			if (!result.success) {
				//如果失败，则提示错误信息
				$.messager.alert('提示', result.message, 'error');
			}
			//无论成功失败，都刷新列表
			$("#tt").treegrid('reload',-1);
		});
	}
}